package com.nf.health.app.activity.my;

import android.os.Bundle;
import android.os.SystemClock;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;

import com.android.volley.VolleyError;
import com.hyphenate.easeui.EaseConstant;
import com.hyphenate.easeui.domain.EaseUser;
import com.nf.health.app.AppModel;
import com.nf.health.app.R;
import com.nf.health.app.activity.global.BaseActivity;
import com.nf.health.app.adapter.MyPersonalDocAdapter;
import com.nf.health.app.adapter.OnMyClickListener;
import com.nf.health.app.chatservice.activity.ChatActivity;
import com.nf.health.app.customview.CircleDialogFactory2;
import com.nf.health.app.customview.DragListView;
import com.nf.health.app.inquiry.docdetail.DocDetailActivity;
import com.nf.health.app.models.PersonalDocModel;
import com.nf.health.app.utils.ActivityUtils;
import com.nf.health.app.utils.ViewUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * Created by Jason on 2016/6/23.
 * 我的私人医生
 */
public class MyPersonalDoctorActivity extends BaseActivity {

    private int pageNo = 1;
    private int pageSize = 20;

    @Bind(R.id.dlv_personal_doc)
    DragListView dlv_personal_doc;
    private MyPersonalDocAdapter myPersonalDocAdapter;
    private List<PersonalDocModel> list;
    private CircleDialogFactory2 circleDialogFactory2;
    private int currentSelectIndex = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setTitleBar(R.layout.titlebar_base);
        setContent(R.layout.activity_personal_doctor);
        ButterKnife.bind(this);
        ViewUtil.setText(this, R.id.titlebar_title_tv, "私人医生");

        list = new ArrayList<PersonalDocModel>();
        provider.requestGetDoctor(pageNo + "", pageSize + "", "doctor");
        dlv_personal_doc.setRefreshableAndLoadMoreable(true, false);

        dlv_personal_doc.setOnRefreshAndLoadMoreListener(new DragListView.onRefreshAndLoadMoreListener() {

            @Override
            public void onRefresh() {
                pageNo = 1;
                initData();
            }

            @Override
            public void onLoadMore() {
                pageNo++;
                initData();
            }
        });

    }

    /*******
     * 初始化数据
     ***/
    private void initData() {
        provider.requestGetDoctor(pageNo + "", pageSize + "", "doctor");
    }

    @Override
    public void handleActionSuccess(String actionName, Object object) {
        dlv_personal_doc.completeRefresh();
        dlv_personal_doc.completeLoadMore();
        if ("doctor".equals(actionName)) {
            list = (List<PersonalDocModel>) object;
            //存储为环信对象
            saveListAsEaseUser(list);
            if (myPersonalDocAdapter == null) {
                myPersonalDocAdapter = new MyPersonalDocAdapter(MyPersonalDoctorActivity.this, list);
                dlv_personal_doc.setAdapter(myPersonalDocAdapter);
            } else {
                myPersonalDocAdapter.setMynotifyDataChanged(list);
            }
            dlv_personal_doc.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    PersonalDocModel model = list.get(position - 1);
                    Bundle bundle = new Bundle();
                    bundle.putString(DocDetailActivity.DOCTORID, model.getDoctorid());
                    ActivityUtils.showActivity(MyPersonalDoctorActivity.this, DocDetailActivity.class, bundle);
                }
            });

        } else if ("getdoctor".equals(actionName)) {
            String responseSre = object.toString();
            if (responseSre.endsWith("\r\n")) {
                responseSre = responseSre.replace("\r\n", "");
            }
            provider.requestGetDoctor(pageNo + "", pageSize + "", "doctor");
            try {
                JSONObject jsonOnbj = new JSONObject(responseSre);
                boolean isSuccess = jsonOnbj.optBoolean("success");
                if (isSuccess) {
                    //开通成功直接跳转到聊天界面,已当前时间作为
                    String etime = jsonOnbj.optJSONObject("data").optString("etime");
                    PersonalDocModel model = list.get(currentSelectIndex);
                    Bundle bundle = new Bundle();
                    bundle.putString(EaseConstant.EXTRA_USER_ID, model.getDoctorid());
                    bundle.putInt(EaseConstant.EXTRA_CHAT_TYPE, EaseConstant.CHATTYPE_SINGLE);
                    if (TextUtils.isEmpty(etime)) {
                        bundle.putString(ChatActivity.EXTRA_DOCTOR_TYPE, "21_" + SystemClock.currentThreadTimeMillis() + 60 * 24 * 60 * 60 * 1000);//21代表私人医生已开通 "_"后面是结束时间(当前+60天)
                    }else {
                        bundle.putString(ChatActivity.EXTRA_DOCTOR_TYPE, "21_" + etime);//21代表私人医生已开通 "_"后面是结束时间(当前+60天)
                    }
                    ActivityUtils.showActivity(MyPersonalDoctorActivity.this, ChatActivity.class, bundle);

                    showToast("开通私人医生成功");
                    PersonalDocModel currentModel = list.get(currentSelectIndex);
                    currentModel.setStatus("1");
                    myPersonalDocAdapter.setMynotifyDataChanged(list);
                } else {
                    String msg = jsonOnbj.optString("msg");
                    showToast(msg);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        if (myPersonalDocAdapter != null) {
            myPersonalDocAdapter.setOnMyClickerListener(new OnMyClickListener() {
                @Override
                public void onClick(final int position, final String flag) {
                    currentSelectIndex = position;
                    if (flag.equals("0")) {////开始咨询 弹框请求接口
                        if (circleDialogFactory2 != null) {
                            circleDialogFactory2.showDialog(MyPersonalDoctorActivity.this);
                        } else {
                            circleDialogFactory2 = new CircleDialogFactory2(MyPersonalDoctorActivity.this).setMyCircleDialogAtter(0.7, 0.4).setNeutralButton(true).setCirclrDialogButtonTextListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    circleDialogFactory2.dismiss();
                                }
                            }, new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    circleDialogFactory2.dismiss();
                                    String id = list.get(currentSelectIndex).getDoctorid();
                                    provider.getrequestGetDoctor(id, "getdoctor");

                                }
                            }, null).setCirclrDialogContent("是否开始60天免费咨询").showDialog(MyPersonalDoctorActivity.this);
                            circleDialogFactory2.getContentMsgCenter();
                        }
                    } else if (flag.equals("1")) {//跳转到聊天界面
                        PersonalDocModel model = list.get(currentSelectIndex);
                        Bundle bundle = new Bundle();
                        bundle.putString(EaseConstant.EXTRA_USER_ID, model.getDoctorid());
                        bundle.putInt(EaseConstant.EXTRA_CHAT_TYPE, EaseConstant.CHATTYPE_SINGLE);
                        bundle.putString(ChatActivity.EXTRA_DOCTOR_TYPE, "21_" + model.getEtime());//21代表私人医生已开通 "_"后面是结束时间
                        ActivityUtils.showActivity(MyPersonalDoctorActivity.this, ChatActivity.class, bundle);
                    }
                }
            });
        }

    }

    /**
     * 把私人医生作为EaseUser保存
     *
     * @param list
     */
    private void saveListAsEaseUser(List<PersonalDocModel> list) {
        EaseUser user;
        for (PersonalDocModel modele : list) {
            user = new EaseUser(modele.getDoctorid());
            user.setNick(modele.getNick());
            user.setAvatar(modele.getHimg());
            AppModel.getInstatnce().saveContact(user);
        }
    }

    @Override
    public void handleActionError(String actionName, String response, VolleyError error) {
        super.handleActionError(actionName, response, error);
    }
    protected void onResume() {
        super.onResume();
        provider.requestGetDoctor(pageNo + "", pageSize + "", "doctor");
    }
}